package com.sise.rsc.controller;

import com.alibaba.fastjson.JSON;
import com.sise.rsc.bean.Result;
import com.sise.rsc.entity.*;
import com.sise.rsc.repository.APackageRepository;
import com.sise.rsc.repository.CourierRepository;
import com.sise.rsc.repository.PackageActionRepository;
import com.sise.rsc.service.CourierService;
import com.sise.rsc.service.PackageService;
import com.sise.rsc.service.TaskService;
import com.sise.rsc.service.UserService;
import com.sise.rsc.util.CacheUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("/courier")
public class CourierController {
    @Resource
    public CourierService courierService;
    @Resource
    private UserService userService;
    @Resource
    public PackageService packageService;
    @Resource
    public APackageRepository aPackageRepository;
    @Resource
    public CourierRepository courierRepository;
    @Resource
    public PackageActionRepository packageActionRepository;
    @Resource
    public TaskService taskService;
    //请求邮差主页面
    @RequestMapping(value = "/index")
    public String courier(HttpSession session, Model model){
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        //获取用户信息

        User user = userService.findUserByUsername(auth.getName());
        int uid=user.getId();
        List<APackage> aPackageList=packageService.findAllAPackageByUserId(uid);
        session.setAttribute("aPackageList",aPackageList);
        session.setAttribute("SESSION_USER",user);
        model.addAttribute("user",user);
        return "courier/index";
    }
    //请求邮差取件页面
    @RequestMapping(value = "/fetch")
    public String  fetch(){
        return "courier/fetch";
    }
    //请求邮差派件页面
    @RequestMapping(value = "/deliver")
    public String  deliver(){
        return "courier/deliver";
    }

    //找到所有邮差
    @RequestMapping(value = "/findAllCourier")
    @ResponseBody
    public String findAllCourier(){
        List<Courier> co = courierService.findAllCourier();
        Courier cb=co.get(0);
        String string= JSON.toJSONString(cb);
        return "courier:"+string;
    }

    //查找所有包裹
    @RequestMapping(value = "/findAllAPackage")
    @ResponseBody
    public String findAllAPackage(){
        String  jsonStr = packageService.findAllAPackageToJson();
        return jsonStr;
    }
    //按照包裹id查找包裹
    @RequestMapping(value = "/findAPackageById")
    @ResponseBody
    public String findAPackageById(int pid){
        String  jsonStr = packageService.findAPackageByIdToJson(pid);
        return jsonStr;
    }
    //查找快递员今天被分配的收取包裹任务
    @RequestMapping(value = "/findAllFetchAPackageByCourierSelf")
    @ResponseBody
    public String findAllFetchAPackageByCourierSelf(HttpSession session){
        User cUser= (User) session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());
        String  jsonStr = packageService.findAllFetchAPackageByCourierIdToJson(courier.getId());
        return jsonStr;
    }
    //查找快递员今天被分配的派送包裹任务
    @RequestMapping(value = "/findAllDeliverAPackageByCourierSelf")
    @ResponseBody
    public String findAllDeliverAPackageByCourierSelf(HttpSession session){
        User cUser= (User) session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());
        String  jsonStr = packageService.findAllDeliverAPackageByCourierIdToJson(courier.getId());
        return jsonStr;
    }
    //上传快递员揽件成功数据
    @RequestMapping(value = "/fetchPackageOK")
    public String savePackageFetchOKAction(HttpSession session,int packageId){
        User cUser= (User) session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());

//        System.out.println("包裹id:"+packageId+" 收件快递员id:"+courier.getId());
        APackage aPackage= aPackageRepository.findAPackageById(packageId);
        PackageAction packageAction=new PackageAction("快件揽收成功", new Date() ,aPackage,courier);
        packageAction.setState(2);//设置为运输中
        int a = packageId;
        aPackageRepository.updateAPackageState(2, a);
        packageActionRepository.save(packageAction);
        //清楚缓存，取消自动取消订单
        CacheUtil.packageList.remove("package:"+aPackage.getNo());
        //更新任务状态：0：完成
        taskService.updateTaskState(0,"取件",packageId,courier.getId());
        return "courier/fetch";
    }
    //上传快递员揽件失败数据
    @RequestMapping(value = "/fetchPackageNO")
    public String savePackageFetchNOAction(HttpSession session,int packageId){
        User cUser= (User) session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());

//        System.out.println("包裹id:"+packageId+" 收件快递员id:"+courier.getId());
        APackage aPackage= aPackageRepository.findAPackageById(packageId);
        PackageAction packageAction=new PackageAction("快件揽收失败", new Date() ,aPackage,courier);
        packageAction.setState(-2);//设置为取件失败
        //清楚缓存，取消自动取消订单
        CacheUtil.packageList.remove("package:"+aPackage.getNo());


        //取消订单
        packageService.updateAPackageStateByNo(-1,aPackage.getNo());
        //更新任务状态：2：未完成
        taskService.updateTaskState(2,"取件",packageId,courier.getId());
        int a = packageId;
        aPackageRepository.updateAPackageState(-2, a);
        packageActionRepository.save(packageAction);
        return "courier/fetch";
    }
    //上传快递员派件成功数据
    @RequestMapping(value = "/deliverPackageOK")
    public String savePackageDeliverOKAction(HttpSession session,int packageId){
        User cUser= (User) session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());

//        System.out.println("包裹id:"+packageId+" 收件快递员id:"+courier.getId());
        APackage aPackage= aPackageRepository.findAPackageById(packageId);
        PackageAction packageAction=new PackageAction("快件派件成功", new Date() ,aPackage,courier);
        packageAction.setState(0);//设置为派件成功
        int a = packageId;
        aPackageRepository.updateAPackageState(0, a);
        packageActionRepository.save(packageAction);
        //更新任务状态：0：完成
        taskService.updateTaskState(0,"派件",packageId,courier.getId());
        return "courier/deliver";
    }
    //上传快递员揽件失败数据
    @RequestMapping(value = "/deliverPackageNO")
    public String savePackageDeliverNOAction(HttpSession session,int packageId){
        User cUser= (User) session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());

//        System.out.println("包裹id:"+packageId+" 收件快递员id:"+courier.getId());
        APackage aPackage= aPackageRepository.findAPackageById(packageId);
        PackageAction packageAction=new PackageAction("快件派件失败", new Date() ,aPackage,courier);
        packageAction.setState(-3);//设置为取件失败
        int a = packageId;

        aPackageRepository.updateAPackageState(-3, a);
        packageActionRepository.save(packageAction);
        //更新任务状态：2：未完成
        taskService.updateTaskState(2,"派件",packageId,courier.getId());
        //判断是否可以再次分配
        if (taskService.findTaskSumByTaskNameAndPackageId("派件",packageId)<3){
            //未超过3次，加入隔日分配派件
            CacheUtil.packageDeliverNextDayList.add(aPackage.getNo());
        }else {
            //超过或等于3次，不再分配,订单状态未异常
            aPackageRepository.updateAPackageState(4,aPackage.getId());
        }
        return "courier/deliver";
    }

    //查找某一个快递员当月的派件量
    @RequestMapping(value = "/getThisMonthFetchNum")
    @ResponseBody
    public int getThisMonthFetchNum(HttpSession session){
        User cUser=(User)session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());
        return courierService.getThisMonthFetchNumByCourierId(courier.getId());
    }
    //查找某一个快递员当月的派件量
    @RequestMapping(value = "/getThisMonthDeliverNum")
    @ResponseBody
    public int getThisMonthDeliverNum(HttpSession session){
        User cUser=(User)session.getAttribute("SESSION_USER");
        Courier courier=courierService.findCourierByUserId(cUser.getId());
        return courierService.getThisMonthDeliverNumByCourierId(courier.getId());
    }
    @RequestMapping(value = "/getWorkingAreaNameByUserId")
    @ResponseBody
    public String getWorkingAreaNameByUserId(HttpSession session){
        User cUser=(User)session.getAttribute("SESSION_USER");
        return courierService.findWorkingAreaByUserId(cUser.getId());
    }

    @RequestMapping("/getWorkingArray")
    @ResponseBody
    public Object getWorkingArray(HttpSession session){
        List<String> data= new LinkedList<>();
        User session_user = (User) session.getAttribute("SESSION_USER");
        if (session_user==null){
            return "无权限1";
        }
        if (!session_user.getRoles().get(0).getAuthority().equals("ROLE_KD"))
            return "无权限2";

        System.out.println("id:"+session_user.getId());
        Courier courier = courierRepository.findCourierByUserId(session_user.getId());
        List<CourierStatus> courierStatus = courierService.findCourierStatusesByStatusAndCourierId("正常",courier.getId());
        if (courierStatus.isEmpty())return "";
        for (CourierStatus status : courierStatus) {
            data.add(Long.toString(status.getTime().getTime()).substring(0,10));
        }

        return data;
    }

    @RequestMapping("/state")
    public String state(){
        return "courier/state";
    }

    @RequestMapping("/changeState")
    @ResponseBody
    public Result changState(HttpSession session){

        User user = (User) session.getAttribute("SESSION_USER");
        if (user == null)
            return new Result(500,"获取用户信息失败，请重新登录后再试！");
        Courier courier = courierRepository.findCourierByUserId(user.getId());


        courierService.changStateToWorking(courier);
        return new Result();


    }



}
